#include<iostream>
#include"CStash.h"

using namespace std;

const int increment = 100;

void Stash::initialize(int sz)
{
	size = sz;
	quantity = 0;
	next = 0;
	storage = 0;
}

int Stash::add(const void* element)
{
	if(next >= quantity)
		inflate(increment);
	int startByte = size * next;
	unsigned char* e = (unsigned char*) element;
	for(int i = 0; i < size; i++)
		storage[startByte + i] = e[i];
	next++;
	return (next - 1);
}

void* Stash::fetch(int index)
{	
	if(index >= next)
		return 0;
	return &(storage[index * size]);
}

int Stash::count()
{
	return next;
}

void Stash::inflate(int increase)
{
	int newQuantity = quantity + increase;
	int newBytes = newQuantity * size;
	int oldBytes = quantity * size;
	unsigned char* newBase = new unsigned char[newBytes];
	for(int i = 0; i < oldBytes; i++)
		newBase[i] = storage[i];
	delete [] storage;
	storage = newBase;
	quantity = newQuantity;

}

void Stash::cleanUp()
{
	if(storage != 0){
		cout<<"freeing the storage!"<<endl;
		delete []storage;
	}
}